// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <melon/chrono/hardware.h>
#include <cstdint>

namespace kumo {
    namespace pollux {
        class SelectivityInfo {
        public:
            void addOutput(uint64_t numOut) {
                numOut_ += numOut;
            }

            float timeToDropValue() const {
                if (numIn_ == numOut_) {
                    return timeClocks_;
                }
                return timeClocks_ / static_cast<float>(numIn_ - numOut_);
            }

            bool operator<(const SelectivityInfo &right) const {
                return timeToDropValue() < right.timeToDropValue();
            }

            uint64_t numIn() const {
                return numIn_;
            }

            uint64_t numOut() const {
                return numOut_;
            }

        private:
            uint64_t numIn_ = 0;
            uint64_t numOut_ = 0;
            uint64_t timeClocks_ = 0;

            friend class SelectivityTimer;
        };

        class SelectivityTimer {
        public:
            SelectivityTimer(SelectivityInfo &info, uint64_t numIn)
                : totalClocks_(&info.timeClocks_),
                  startClocks_(melon::hardware_timestamp()) {
                info.numIn_ += numIn;
            }

            ~SelectivityTimer() {
                *totalClocks_ += melon::hardware_timestamp() - startClocks_;
            }

            void subtract(uint64_t clocks) {
                startClocks_ += clocks;
            }

        private:
            uint64_t *const totalClocks_;
            uint64_t startClocks_;
        };
    } // namespace pollux
} // namespace kumo
